<template>
  <div class="user-list">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.telephone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input
            v-model="searchForm.nickName"
            placeholder="请输入昵称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <el-card class="list-card">
      <el-table
        :data="userList"
        style="width: 100%"
        v-loading="loading"
        border
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="user-detail">
              <div class="detail-item">
                <span class="label">邮箱：</span>
                <span class="value">{{ row.email || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">注册时间：</span>
                <span class="value">{{ formatDate(row.createTime) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">最后登录：</span>
                <span class="value">{{ formatDate(row.lastLoginTime) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar
                :size="40"
                :src="row.icon"
                :alt="row.nickName"
              />
              <div class="user-detail">
                <div class="nickname">{{ row.nickName }}</div>
                <div class="telephone">{{ formatTelephone(row.telephone) }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orderCount" label="订单数" width="100" />
        <el-table-column prop="totalAmount" label="消费金额" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.totalAmount || 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import service from '@/utils/request'
import { getUserList, deleteUser } from '@/api/user'

const router = useRouter()
const loading = ref(false)

// 搜索表单
const searchForm = ref({
  telephone: '',
  nickName: '',
  timeRange: []
})

// 用户列表
const userList = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化手机号
const formatTelephone = (telephone) => {
  if (!telephone) return '未设置'
  return telephone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      telephone: searchForm.value.telephone,
      nickName: searchForm.value.nickName,
      startTime: searchForm.value.timeRange?.[0],
      endTime: searchForm.value.timeRange?.[1]
    }
    const res = await getUserList(params)
    userList.value = Array.isArray(res) ? res : []
    total.value = userList.value.length
  } catch (error) {
    console.error('加载用户列表失败：', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadUserList()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    telephone: '',
    nickName: '',
    timeRange: []
  }
  handleSearch()
}

// 查看用户详情
const handleEdit = (row) => {
  router.push(`/jiang/users/edit/${row.id}`)
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${row.nickName}"吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteUser(row.id)
    
    ElMessage.success('用户已删除')
    loadUserList()
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除失败：', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}该用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await service.put(`/admin/users/${row.id}/status`, {
      status: row.status === 1 ? 0 : 1
    })
    
    ElMessage.success(`用户已${row.status === 1 ? '禁用' : '启用'}`)
    loadUserList()
  } catch (error) {
    if (error === 'cancel') return
    console.error('操作失败：', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadUserList()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUserList()
}

// 新增用户
const handleAdd = () => {
  router.push('/jiang/users/add')
}

onMounted(() => {
  loadUserList()
})
</script>

<style lang="scss" scoped>
.user-list {
  .operation-bar {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    
    .search-form {
      flex: 1;
    }
    
    .toolbar {
      margin-left: 20px;
    }
  }

  .list-card {
    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .user-detail {
        .nickname {
          margin-bottom: 4px;
          color: var(--el-text-color-primary);
        }

        .telephone {
          color: var(--el-text-color-secondary);
          font-size: 13px;
        }
      }
    }

    .user-detail {
      padding: 20px;
      background-color: var(--el-fill-color-light);

      .detail-item {
        margin-bottom: 12px;
        font-size: 14px;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          color: var(--el-text-color-secondary);
          margin-right: 8px;
        }

        .value {
          color: var(--el-text-color-primary);
        }
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
